<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>企业微信信息化平台</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/index.css}">
</head>
<body>

<div class="layui-fluid " style="max-height: calc(100vh); overflow:auto;">
    <div class="layui-tab" lay-filter="test1">
        <ul class="layui-tab-title" style="height: calc(5vh);">
            <li class="layui-this" lay-id="111">待办事项</li>
            <li lay-id="222">支持数据</li>
            <li lay-id="333">客户数据</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-fluid " style="overflow:no-display">
                    <!--        style="max-height: calc(100vh); overflow:auto;"-->
                    <div class="layui-col-md1">
                        <ul>
                            <li>
                                <form class="layui-form" lay-filter="formDemo1">
                                    <label>
                                        <select name="all_engineer" lay-verify="" lay-search lay-filter="formDemo"
                                                id="all_engineer">
                                            <option value="all_engineer">全部员工</option>
                                        </select>
                                    </label>
                                    <label for="test10">日期时间范围</label>
                                    <input type="text" class="layui-input" id="test10" style="font-size:1%">
                                </form>
                            </li>
                            <li>
                                <ul class="layui-menu" id="docDemoMenu1">
                                    <li lay-options="{type:'problem',status:0, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title" id="problemOn">未解决问题</div>
                                    </li>
                                    <li lay-options="{type:'message',status:0, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title" id="messageOn">未响应消息</div>
                                    </li>

                                    <li lay-options="{type: 'message',status:1, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title">已响应消息</div>
                                    </li>
                                    <li lay-options="{type:'problem',status:1, engineer_id:'all_engineer'}">
                                        <div class="layui-menu-body-title">已解决问题</div>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <div class="layui-panel" id="tbOverTime">
                                    <button type="button" class="layui-btn layui-btn-sm  layui-btn-danger"
                                            id="titleNeedToReply">要添加问题状态的数量
                                    </button>
                                    <table class="layui-table" lay-size="sm">
                                        <colgroup>
                                            <col>
                                        </colgroup>
                                        <thead>
                                        <tr>
                                            <th style="text-align: center ">人员</th>
                                            <th style="text-align: center ">数量</th>
                                        </tr>
                                        </thead>
                                        <tbody id="tbodyNeedAddProblemStatus">
                                        </tbody>
                                    </table>
                                    <table class="layui-table" lay-size="sm">
                                        <colgroup>
                                            <col>
                                        </colgroup>
                                        <thead>
                                        <tr>
                                            <th style="text-align: center ">人员</th>
                                            <th style="text-align: center ">数量</th>
                                        </tr>
                                        </thead>
                                        <tbody id="overTimeData">
                                        </tbody>
                                    </table>
                                    <label for="input" style="display: none">复制元素转站</label>
                                    <textarea id="input" class="layui-hide">复制元素转站</textarea>
                                </div>
                            </li>
                            <li>
                                <a th:href="@{/logout}" class="layui-btn" target="_self">登出账号</a>
                                <!--            <a th:href="@{/changePassword}" class="layui-btn" target="_blank">修改密码</a>-->
                        </ul>
                    </div>
                    <div class="layui-col-md3" style="max-height: calc(95vh); overflow:auto; ">

                        <table class="layui-table">
                            <colgroup>
                                <col>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>群名</th>
                            </tr>
                            </thead>
                            <tbody id="group_list">
                            </tbody>
                        </table>
                    </div>
                    <div class="layui-col-md8 " style="max-height: calc(95vh); overflow:auto; " id="div1">
                        <div class="layui-form">
                            <div id="message_card"></div>
                            <table class="layui-table">
                                <colgroup>
                                    <col style="width: 40%">
                                    <col style="width: 4%">
                                    <col style="width: 7%">
                                    <col style="width: 4%">
                                </colgroup>
                                <thead>
                                <tr>
                                    <th id="thGroupName" style="text-align: center ">问题</th>
                                    <th>工程师</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="message_list">

                                </tbody>
                                <!--                <tfoot id="tFoot"></tfoot>-->
                            </table>
                        </div>
                    </div>

                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-btn-group">
                    <button type="button" class="layui-btn layui-btn-normal" id="nextMonth"
                            onclick="dataChange(this.id)">下个月
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" id="lastMonth"
                            onclick="dataChange(this.id)">上个月
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" id="lastWeek"
                            onclick="dataChange(this.id)">上周
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" id="nextWeek"
                            onclick="dataChange(this.id)">下周
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" id="tbSortDesc"
                            onclick="tbSortDesc(this.id)">降序
                    </button>
                </div>

                <div class="page-item">
                    <label for="dateChooseEngineerData"></label>
                    <input type="text" class="layui-input" id="dateChooseEngineerData" style="font-size:1%">
                    <div class="container-fluid">
                        <div class="layui-col-md8">
                            <div class="page-item" id="engineerData"></div>
                        </div>
                    </div>
                    <!--                    <table class="layui-hide" id="groupData" lay-filter="test4"></table>-->
                </div>
            </div>
            <div class="layui-tab-item">
                <iframe th:src="@{clientData}" class="x-iframe" style="height: calc(85vh); width:100%"></iframe>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/layui/jquery-3.6.0.min.js}"></script>
<script th:src="@{/layui/layui.js}"></script>
<script>
    layui.use(['form'], function () {
        let form = layui.form
        $.ajax({
            url: "/sel_all_engineer",
            type: "get",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                let engineerList = data['engineers'];
                let currentUser = data['currentUser']['name'];
                if (data != null) {
                    let selAllEngineer = document.getElementById("all_engineer");
                    for (let i = 0; i < engineerList.length; i++) {
                        selAllEngineer.innerHTML += '<option value="' + engineerList[i]['name'] + '">' + engineerList[i]['name'] + '</option>'
                    }
                    form.render('select');  //重新渲染
                    changeEngineer(currentUser);
                }
            }
        })
    })
    // 默认选择的消息类型、消息状态、工程师id(默认是全部门)、群id、群名、消息id
    let pageOptions = {
        type: "problem",
        status: "0",
        engineer_id: "all_engineer",
        cp_id: "",
        processorDepartment: 0,
        cp_name: "",
        hq: "",
        time: "0",
        endTime: '0'
    }
    let div_message_list = "<tr id='hq_id'>\n" +
        "                        <td onclick=\"change_group_name('群名')\"> text</td>\n" +
        "                        <td>engineer</td>\n" +
        "                        <td>time</td>\n" +
        "                        <td>button</td>\n" +
        "                    </tr>"


    function change_group_name(group_name) {
        document.getElementById('thGroupName').innerText = group_name
        let input = document.getElementById("input");
        input.value = group_name; // 修改文本框的内容
        input.select(); // 选中文本
        document.execCommand("copy"); // 执行浏览器复制命令
        // alert("复制成功");
    }


    // let engineerName = '[[${engineerName}]]'/'all_engineer';
    let engineerName = $("#all_engineer option:selected").val()

    if (engineerName !== '' && engineerName !== null) {
        pageOptions.engineer_id = engineerName;
    } else {
        pageOptions.engineer_id = 'all_engineer';
    }
    let tempFormStatus = {};
    //群名列表
    let group_list = document.getElementById("group_list");
    //<button type="button"  onclick="selMsgByGroup(id,value,'待处理数量')" class="layui-btn layui-btn-normal layui-btn-fluid" id='cp_id' value='群名'>cp_name</button>
    //<span class="layui-badge layui-bg-cyan">数量</span>
    // 群名列表按钮所需单元格元素
    let div_group_msg = "<tr>\n" +
        "                    <td><button type=\"button\"  onclick=\"selMsgByGroup(id,value,'待处理数量')\" class=\"layui-btn layui-btn-normal layui-btn-fluid\" id='cp_id' value='群名'>cp_name</button></td>\n" +
        "                </tr>";
    //解决按钮所需元素
    let button_update_msg_status = "<button type=\"button\"  onclick=\"update_message_status('msg_id','engineer')\" class=\"layui-btn-sm  layui-bg-gray layui-btn-fluid\" >关闭</button>";
    let laypage;
    let layer;
    /*填充表格的初始化参数*/
    let tb_obj_data = {
        "id": "engineerData",
        "sort": {
            "key": "talkCnt",
            "sort": false
        },
        "tb_class": "layui-table",
        "title": [{
            "key": "name",
            "value": "员工",
            "class": "layui-bg-red"
        }, {
            "key": "talkCnt",
            "value": "发言数量(总数)",
            "avg_sum":"sum",
            "class": "layui-bg-orange"
        },
            {
                "key": "resCntW",
                "value": "工作时间响应数量",
                "avg_sum":"sum",
                "class": "layui-bg-green"
            }, {
                "key": "resAvgW",
                "isFloat": true,
                "value": "工作时间平均响应时间",
                "avg_sum":"avg",
                "class": "layui-bg-cyan"
            }, {
                "key": "resCnt",
                "value": "非工作时间响应数量",
                "avg_sum":"sum",
                "class": "layui-bg-cyan"
            }, {
                "key": "resAvg",
                "isFloat": true,
                "value": "非工作时间平均响应时间",
                "avg_sum":"avg",
                "class": "layui-bg-cyan"
            }, {
                "key": "needPro",
                "value": "所有未解决问题",
                "avg_sum":"sum",
                "class": "layui-bg-cyan"
            }, {
                "key": "newPro",
                "value": "周期内新增问题数量",
                "avg_sum":"sum",
                "class": "layui-bg-cyan"
            }, {
                "key": "proCnt",
                "value": "周期内解决问题数量",
                "avg_sum":"sum",
                "class": "layui-bg-cyan"
            }, {
                "key": "proAvg",
                "isFloat": true,
                "value": "周期内问题平均时间（小时）",
                "avg_sum":"avg",
                "class": "layui-bg-cyan"
            }, {
                "key": "proOtherCnt",
                "value": "周期内由他人记录的问题",
                "class": "layui-bg-cyan",
                "avg_sum":"sum",
            }, {
                "key": "close",
                "isFloat": true,
                "value": "问题关闭率（本部门）",
                "class": "layui-bg-cyan",
                "avg_sum":"sum",
            }, {
                "key": "pro_avg_other",
                "isFloat": true,
                "value": "其他部门协助解决问题平均时间",
                "avg_sum":"avg",
                "class": "layui-bg-cyan"
            }, {
                "key": "pro_cnt_other",
                "isFloat": true,
                "value": "其他部门协助解决问题数量",
                "avg_sum":"sum",
                "class": "layui-bg-cyan"
            }],
        "group": [],
        "isGroupDisplay": true,
        allData: {}
    }

    engineerData = {
        elem: '#engineerData',
        limit: 15,
        cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        cols: [
            [
                {field: 'name', title: '员工', width: 80, sort: true}
                , {field: 'talkCnt', title: '发言数量', width: 100, sort: true}
                , {field: 'resCntW', title: '工作时间响应数量', width: 150, sort: true}
                , {field: 'resAvgW', title: '工作时间平均响应时间', width: 170, sort: true}
                , {field: 'resCnt', title: '非工作时间响应数量', width: 175, sort: true}
                , {field: 'resAvg', title: '非工作时间平均响应时间', width: 180, sort: true}
                , {field: 'needPro', title: '所有未解决问题', width: 155, sort: true}
                , {field: 'newPro', title: '周期内新增问题数量', width: 135, sort: true}
                , {field: 'proCnt', title: '周期内解决问题数量', width: 135, sort: true}
                , {field: 'proAvg', title: '周期内问题平均时间（小时）', width: 215, sort: true}
                , {field: 'proOtherCnt', title: '周期内由他人记录的问题', width: 180, sort: true}
            ]
        ],
        data: [],
        // done: function (res, curr, count) {
        done: function (res) {
            let that = this.elem.next();
            res.data.forEach(function (item, index) {
                if (item.name === '部门') {
                    let tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']");
                    tr.css("background-color", "yellow");
                    // console.log(item, index)
                }
            })
        }
    };
    let date = {
        month: 0,
        year: 0,
        week: 0,
        day: 0,
        optionCode: 'allDate',
        startTime: null,
        endTime: null,
        period: null
    }

    let weekCount = 6;

    function dataChange(clickId) {
        date.optionCode = 'period';
        // console.log(date)
        switch (clickId) {
            case 'nextMonth':
                date.month++;
                date["period"] = 'month';
                break;
            case 'lastMonth':
                date.month--;
                date["period"] = 'month';
                break;
            case 'nextWeek':
                if (date.week < weekCount) {
                    date.week++;
                    date["period"] = 'week';
                }
                break;
            case 'lastWeek':
                if (date.week > 1) {
                    date.week--;
                    date["period"] = 'week';
                }
                break;
            case 'now':
                break;
            default:
                console.log('error')
        }
        apiEngineerAvgTime(date)
    }

    function engineerAvgTime(value) {
        if (value !== null) {
            let startTime = value.substring(0, 19);
            let endTime = value.substring(22);
            let dataOption = {};
            dataOption['startTime'] = startTime;
            dataOption['endTime'] = endTime;
            dataOption['optionCode'] = 'allData'
            apiEngineerAvgTime(dataOption)
        }
    }

    function apiEngineerAvgTime(data) {
        $.ajax({
            url: "/engineerAvgTime",
            type: "get",
            data: {
                dataOption: JSON.stringify(data)
            },
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                addMessage(data);
            }
        })
    }

    function tbSortDesc(id) {
        let elementById = document.getElementById(id);
        if (tb_obj_data.sort.sort) {
            tb_obj_data.sort.sort = false
            elementById.innerText = `降序`

        } else {
            tb_obj_data.sort.sort = true
            elementById.innerText = `升序`
        }
        addTable(tb_obj_data)
    }

    /*custom添加表格*/
    function addTable(tb_object) {
        /*填充组头数据*/
        if (tb_object['group'] !== undefined) {
            let groups = tb_object['group'];
            groups.forEach((groupsValue, groupsKey) => {
                groupsValue.context.sort(compareSon(tb_object.sort.key, tb_object.sort.sort))
                /*遍历组头（组头可能有多个）*/
                groupsValue.head.forEach((headValue, headKey) => {
                    /*遍历表头，拿到key获取组头的对应值*/
                    tb_object.title.forEach((tb_title_value) => {
                        /*组头的当前值*/
                        let temp = headValue[tb_title_value.key];
                        /*组头的临时值*/
                        let tempGroupValue = 0;
                        /*如果组头的当前值为空，则为组头赋值*/
                        if (temp === undefined || temp === '' || temp === null) {
                            groupsValue.context.forEach((contextValue) => {
                                tempGroupValue += contextValue[tb_title_value.key]
                            })
                            if (tb_title_value.avg_sum==='sum'){
                            }else if (tb_title_value.avg_sum==='avg'){
                                tempGroupValue= (tempGroupValue / groupsValue.context.length);
                            }
                            tb_object.group[groupsKey].head[headKey][tb_title_value.key]=tempGroupValue
                        }
                    })
                })
            })
        } else {
            return;
        }
        tb_object.group.sort(compareParent(tb_object.sort.key, tb_object.sort.sort));
        creatTable(tb_object);
    }

    /*比较父级*/
    function compareParent(p, desc) { //这是比较函数,比较二级头
        return function (m, n) {
            let a = m["head"][0][p];
            let b = n["head"][0][p];
            if (desc) {
                return a - b;
            } else {
                return b - a; //降序
            }
        }
    }

    /*比较子集*/
    function compareSon(p, desc) {
        return function (m, n) {
            let a = m[p];
            let b = n[p];
            if (desc) {
                return a - b;
            } else {
                return b - a; //降序
            }
        }
    }

    /*添加表头排序事件*/
    document.body.onclick = function (event) {
        let id = event.target.id;
        for (let tbHead of tb_obj_data.title) {
            if (tbHead.key === id) {
                tb_obj_data.sort.key = id
                // tb_obj_data.sort.sort = !tb_obj_data.sort.sort
                addTable(tb_obj_data)
                return
            }
        }
    }

    function addMessage(data) {
        engineerData.data = data['data'];
        weekCount = data['weekCount'] + 1;
        engineerData.limit = data['data'].length

        let dateChooseEngineerData = document.getElementById("dateChooseEngineerData")
        if (data["endTime"] === null || data["startTime"] === null) {
        } else {
            dateChooseEngineerData.value = data["startTime"] + ' - ' + data["endTime"]
        }
        tb_obj_data.group[0] = {
            "head": [
                {
                    "name": "部门"
                }
            ],
            "context": data['data']
        }
        addTable(tb_obj_data)
        /*
        layui.use('table', function () {
            let table = layui.table;
            table.render(engineerData);
        });*/
    }

    /*小数转百分比*/
    function toPercent(point) {
        if (point >= 1) {
            return 0;
        }
        let str = Number(point * 100).toFixed(2);
        str += "%";
        return str;
    }

    /*数据解析并加入到dom*/
    function creatTable(table_object) {
        let title, groups, title_ele = ``, group_ele = ``, id;
        if (table_object['id'] !== undefined) {
            id = table_object['id'];
        } else {
            return;
        }
        title_ele += `<table class="` + table_object.tb_class + `">`;
        if (table_object['title'] !== undefined) {
            title = table_object['title'];
            title_ele += `<tr >`
            for (let titleElement of title) {
                title_ele += `<th class="` + titleElement.class + ` tb_head" id="` + titleElement.key + `">` + titleElement.value + `</th>`
            }
            title_ele += `</tr>`
        } else {
            return;
        }
        if (table_object['group'] !== undefined) {
            groups = table_object['group'];
            for (let group of groups) {
                for (let headElement of group.head) {
                    group_ele += `<tr class="layui-bg-black">`
                    for (let titleElement of title) {
                        /*如果是小数则保留两位*/
                        let newVar1 = headElement[titleElement.key] % 1 > 0
                            ? headElement[titleElement.key].toFixed(2) : headElement[titleElement.key];

                        if (titleElement.key === 'close') {
                            newVar1 = toPercent(newVar1)
                        }
                        group_ele += `<td class="` + titleElement.class + `">` + newVar1 + `</td>`
                    }
                    group_ele += `</tr>`
                }
                for (let contextElement of group.context) {
                    group_ele += `<tr>`
                    /*遍历表头，获取一行每一单元格的值*/
                    for (let titleElement of title) {
                        let newVar = contextElement[titleElement.key] % 1 > 0
                            ? contextElement[titleElement.key].toFixed(3) : contextElement[titleElement.key];
                        // if (titleElement.key === 'close') {
                        //     newVar = toPercent(newVar)
                        // }
                        group_ele += `<td>`
                            + newVar
                            + `</td>`
                    }
                    group_ele += `</tr>`
                }
            }
            title_ele += group_ele;
        } else {
            return;
        }
        title_ele += `</table>`;
        let elementById = document.getElementById(id);
        elementById.innerHTML = title_ele;
    }

    // {"engineer_name":"","group_name":"","type":"problem","status":"all"}
    layui.use('form', function () {
        const form = layui.form;
        form.on('select(formDemo)', function (data) {
            pageOptions.engineer_id = data.value
            // console.log('选择的员工id' + pageOptions.toString()); //得到被选中的值
            ask_all_group_message(pageOptions);
            ask_all_message(pageOptions);
        });
    });
    layui.use(['laypage', 'layer'], function () {
        laypage = layui.laypage;
        layer = layui.layer;
        //完整功能
        laypage.render({
            elem: 'tFoot'
            , count: 100
            , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            , jump: function (obj) {
                // console.log(obj)
            }
        });
    })
    layui.use('laydate', function () {
        const layDate = layui.laydate;
        let dateInfo = {
            elem: '#dateChooseEngineerData'
            , type: 'datetime'
            , range: ['#startDate', '#endDate']
            , value: '2021-08-01 00:00:00 - 2021-08-30 00:00:00'
            , trigger: 'mousedown'
            , done: function (value) {
                engineerAvgTime(value)
            }
        }
        //日期时间范围
        layDate.render(dateInfo);
        layDate.render({
            elem: '#test10'
            , type: 'datetime'
            , range: true
            , trigger: 'mousedown'
            , done: function (value) {
                let time = value.substring(0, 19)
                let endTime = value.substring(22)
                // console.log("value" + value)
                if (value !== '') {
                    pageOptions.time = Date.parse((new Date(time).toString())) / 1000
                    pageOptions.endTime = Date.parse((new Date(endTime).toString())) / 1000
                }
                // console.log(pageOptions)
                ask_all_group_message(pageOptions)
                ask_all_message(pageOptions)
            }
        });
    });

    //修改选中的员工
    function changeEngineer(name) {
        $("#all_engineer").val(name);
        pageOptions.engineer_id = name;
        // console.log('选择的员工id' + pageOptions.toString()); //得到被选中的值
        ask_all_group_message(pageOptions);
        ask_all_message(pageOptions);
        //渲染下拉框
        layui.use('form', function () {
            const form = layui.form;
            form.render("select");
        });
    }


    function BTNNameEngineer(name) {
        changeEngineer(name);
    }

    function addOverTimeData(data, ElementId) {
        let tbModel = `<tr>
                            <td style="text-align: center ">name</td>
                            <td style="text-align: center ">cnt</td>
                        </tr>`;
        let tbodyNeedAddProblemStatus = document.getElementById(ElementId)
        let temp = ''
        tbodyNeedAddProblemStatus.innerHTML = ''
        for (let i = 0; i < data.length; i++) {
            // temp = tbModel.replace('name', data[i]['name'])
            // temp = temp.replace('cnt', data[i]['allCnt']);
            data.sort
            if (typeof (data[i]['name']) !== "undefined" && typeof (data[i]['allCnt']) !== "undefined") {
                temp = tbModel.replace('name', data[i]['name']);
                if (i > 0) {
                    temp = temp.replace('cnt', '保密');
                } else {
                    temp = temp.replace('cnt', data[i]['allCnt']);
                }
            }
            tbodyNeedAddProblemStatus.innerHTML += temp;
        }
    }

    function addTbody(data, ElementId) {
        let tbModel = '<tr>\n' +
            '                    <td>\n' +
            '                        <button  class="layui-btn   layui-btn-danger layui-btn-fluid layui-btn-sm"\n' +
            '                                onclick="BTNNameEngineer(\'engineerName\')">engineer_name\n' +
            '                        </button>\n' +
            '                    </td>\n' +
            '                    <td style="text-align: center ">\n' +
            '                      problemNum  \n' +
            '                    </td>\n' +
            '                </tr>'
        let tbodyNeedAddProblemStatus = document.getElementById(ElementId)
        let temp = ''
        tbodyNeedAddProblemStatus.innerHTML = ''
        for (let i = 0; i < data.length; i++) {
            temp = tbModel.replace('engineerName', data[i]['engineer'])
            temp = temp.replace('engineer_name', data[i]['engineer']);
            if (typeof (data[i]['problemNum']) !== "undefined") {
                temp = temp.replace('problemNum', data[i]['problemNum']);
            } else if (typeof (data[i]['needToReplyNum']) !== "undefined") {
                temp = temp.replace('problemNum', data[i]['needToReplyNum']);
            }
            tbodyNeedAddProblemStatus.innerHTML += temp;
        }
    }

    function ask_allNeedAddProblemStatus_engineer() {
        $.ajax({
            url: "/needAddProStatusNum"
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                addTbody(data, 'tbodyNeedAddProblemStatus')
            }
        })
    }

    function ask_over_time_data() {
        $.ajax({
            url: "/getOverTimeData"
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                console.log(data)
                addOverTimeData(data, 'overTimeData')
            }
        })
    }

    //菜单栏事件，获取选择的消息类型与消息状态
    layui.use('dropdown', function () {
        let dropdown = layui.dropdown;
        //菜单点击事件，其中 docDemoMenu1 对应的是菜单结构上的 id 指
        dropdown.on('click(docDemoMenu1)', function (data) {
            pageOptions.type = data.type
            pageOptions.status = data.status
            document.getElementById("message_list").innerHTML = ''
            ask_all_group_message(pageOptions)
            ask_all_message(pageOptions)
            document.getElementById('thGroupName').innerText = '群名'
            let titleNeedToReply = document.getElementById('titleNeedToReply')
            if (pageOptions.status === 0) {
                if (pageOptions.type === 'problem') {

                    titleNeedToReply.innerHTML = '要添加问题状态的数量';
                    ask_allNeedAddProblemStatus_engineer();
                } else if (pageOptions.type === 'message') {
                    titleNeedToReply.innerHTML = '超时未响应的数量';
                    ask_allNeedReplyMessage();
                } else {
                }
            }
        });
    });
    layui.use('element', function () {
        const element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块

        //触发事件
        element.on('tab(tabChange)', function (data) {
            // console.log(data);
        });
    })

    function ask_allNeedReplyMessage() {
        // console.log('超时未响应的数量')
        $.ajax({
            url: "/needToReplyNum"
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                addTbody(data, "tbodyNeedAddProblemStatus")
            }
        })
    }

    function ask_all_message(options) {
        $.ajax({
            url: "/ask_all_message"
            , data: {
                data: JSON.stringify(options)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                console.log(options)
                console.log(data)
                let length = 0
                if (data !== null || data !== '') {
                    length = data.length
                }
                if (options.type === 'problem' && options.status === 0) {
                    let elementById = document.getElementById('problemOn');
                    elementById.innerText = '未解决问题' + '[' + length + ']';
                } else if (options.type === 'message' && options.status === 0) {
                    let elementById1 = document.getElementById('messageOn');
                    elementById1.innerText = '未响应消息' + '[' + length + ']';
                }
                add_msg_list(data)
            }
        })
    }

    let form_status =
        `<div class="layui-tab" lay-filter="demo" lay-allowclose="true">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="11">添加状态</li>
            <li lay-id="22">补充问题</li>
            <li lay-id="33">分配给其他人</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show"><table class="layui-table" style="display: none">
                    <colgroup>
                        <col style="width:300px">
                        <col style="width:100px">
                        <col style="width:100px">
                        <col style="width:80px">
                        <col>
                    </colgroup>
                    <thead>
                    <tr>
                        <th>状态</th>
                        <th>人员</th>
                        <th>时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="tb_problem_status">tbProblemStatus
                    </tbody>
                </table>
                <textarea placeholder="请输入内容" class="layui-textarea"
                          id='addMsgStatusAreaId'></textarea>
                <button type="button" class="layui-btn layui-btn-danger" onclick="add_msg_status_content('AMSID')">更新状态</button>
                <button type="button" class="layui-btn layui-btn-danger" onclick="sameYesterday('SYDID')">和上次相同</button>
            </div>
            <div class="layui-tab-item">
                <textarea placeholder="请输入内容" class="layui-textarea" id='updateTextAreaId' style='height: auto'>changeProblemContent</textarea>
                <button type="button" class="layui-btn layui-btn-danger" onclick="update_message_content('tAId')">提交修改
                </button>
            </div>
            <div class="layui-tab-item">
               问题归属人: changeEngineer
               <br>
               问题分配人: problemDistribute
            </div>
        </div>
    </div>`

    //问题状态与昨日相同
    function sameYesterday(SYDID) {
        console.log(111 + SYDID)
        let msg = {}
        msg.hq = SYDID.substring(3)
        // msg.engineer = engineer_name
        $.ajax({
            url: "/sameYesterday"
            , data: {data: JSON.stringify(msg)}
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function () {
                layui.use('layer', function () {
                    layer.closeAll()
                });
                add_msg_status(SYDID.substring(3), 'engineer')
                // updateProblemStatusTable(add_msg_status_content_id.substring(3))
            }
        })

    }

    //添加问题当前状态
    function add_msg_status_content(add_msg_status_content_id) {
        let addMsgStatusContentId = document.getElementById(add_msg_status_content_id)
        if (addMsgStatusContentId.value !== null && addMsgStatusContentId.value !== '') {
            let msg = {}
            msg.hq = add_msg_status_content_id.substring(3)
            msg.msgStatusContentValue = addMsgStatusContentId.value
            // msg.engineer = engineer_name
            $.ajax({
                url: "/add_problem_status"
                , data: {data: JSON.stringify(msg)}
                , type: "get"
                , dataType: "json"
                , contentType: "application/json;charset=utf-8"
                , success: function () {
                    layui.use('layer', function () {
                        layer.closeAll()
                    });
                    add_msg_status(add_msg_status_content_id.substring(3), 'engineer')
                    // updateProblemStatusTable(add_msg_status_content_id.substring(3))
                }
            })
        }

    }

    //修改问题内容
    function update_message_content(msgId) {
        let updateTextArea = document.getElementById(msgId)
        let data = {}
        data.hq = msgId.substring(7)
        data['text'] = updateTextArea.value
        $.ajax({
            url: "/change_problem"
            , data: {
                data: JSON.stringify(data)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function () {
                layui.use('layer', function () {
                    layer.closeAll()
                });
                add_msg_status(msgId.substring(7), 'engineer')
            }
        })
    }

    function del_pro_status(idProblemStatus, hq) {
        $.ajax({
            url: "/del_pro_status"
            , data: {
                idProblemStatus: idProblemStatus
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                console.log(data)
                layer.closeAll();
                add_msg_status(hq);
            }
        })
    }

    function add_msg_status(msg_id, engineer) {
        updateProblemStatusTable(msg_id)
        $.ajax({
            url: "/selMsgByHq"
            , data: {
                hq: msg_id
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                console.log(data)
                let msg_by_hq = data["selMsgByHq"]
                let tb_problem_status_content = data["problemStatusByHq"]
                let temp = '';
                let pro_status = `
                <tr>
                <td>statusContent</td>
                <td>engineer</td>
                <td>timeFormat</td>
                <td><button type="button" class="layui-btn layui-btn-danger" onClick="del_pro_status('idProblemStatus','pro_hq')">删除</button></td>
                </tr>
                `;

                for (let i = 0; i < tb_problem_status_content.length; i++) {
                    let j = pro_status.replace("statusContent", tb_problem_status_content[i]['statusContent']);
                    j = j.replace('engineer', tb_problem_status_content[i]['engineer']);
                    j = j.replace('idProblemStatus', tb_problem_status_content[i]['idProblemStatus']);
                    j = j.replace('timeFormat', tb_problem_status_content[i]['timeFormat'])
                    j = j.replace('pro_hq', tb_problem_status_content[i]['hq'])
                    temp += j;
                }
                // console.log(temp)
                // console.log(msg_by_hq, tb_problem_status_content)
                tempFormStatus = form_status.replace('changeProblemContent', msg_by_hq.text)
                tempFormStatus = tempFormStatus.replace('changeEngineer', msg_by_hq.engineer)
                tempFormStatus = tempFormStatus.replace('problemDistribute', msg_by_hq['speaker'])

                tempFormStatus = tempFormStatus.replace('tAId', "update_" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('updateTextAreaId', "update_" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('AMSID', "add" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('SYDID', "add" + msg_by_hq.hq)
                tempFormStatus = tempFormStatus.replace('idProblemStatus', msg_by_hq['idProblemStatus'])
                tempFormStatus = tempFormStatus.replace('addMsgStatusAreaId', "add" + msg_by_hq.hq)
                // console.log(msg_by_hq["msgStatus"])
                if (temp !== "" && temp != null) {
                    tempFormStatus = tempFormStatus.replace('display: none', '')
                    // tempFormStatus = tempFormStatus.replace('tbProblemStatus', tableUpdateProblemStatus)
                    tempFormStatus = tempFormStatus.replace('tbProblemStatus', temp)
                    // tdParsing(msg_by_hq["msgStatus"])
                } else {
                    tempFormStatus = tempFormStatus.replace('tbProblemStatus', "")
                }
                layui.use('layer', function () {
                    layer.open({
                        type: 1,
                        title: false,
                        scrollbar: false,
                        content: tempFormStatus,
                        area: ['80%', '60%']
                    });
                    layui.use('form', function () {
                        const form = layui.form;
                        //表单取值
                        layui.$('#LAY-component-form-eval').on('click', function () {
                            let data = form.val('solution_input');
                            if (data['solution'] !== "") {
                                data['engineer'] = engineer
                                data['hq'] = msg_id
                                data['type'] = pageOptions.type
                                data['status'] = pageOptions.status
                                ajax_update_status(data)
                                parent.layer.closeAll()
                                layer.msg('已经解决啦');
                                document.getElementById(msg_id).innerHTML = ''
                                //关闭悬浮框
                            } else {
                                layer.msg('你还没有输入解决方案哦');
                            }
                        });
                    });
                })
            }
        })
    }

    let tableUpdateProblemStatus = ''

    function get_tableUpdateProblemStatus(data) {
        let tempTable = ''
        for (let i = 0; i < data.length; i++) {
            tempTable = tempTable + '<tr>'
            tempTable = tempTable + '<td>' + data[i]['statusContent'] + '</td>'
            tempTable = tempTable + '<td>' + data[i]['engineer'] + '</td>'
            tempTable = tempTable + '<td>' + data[i]['timeFormat'] + '</td>'
            tempTable = tempTable + '</tr>'
        }
        tableUpdateProblemStatus = tempTable
    }

    function updateProblemStatusTable(hq) {
        $.ajax({
            url: "/problemStatusByHq"
            , data: {
                hq: hq
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                get_tableUpdateProblemStatus(data)
            }
        })
    }

    let form_solution = "<form class='layui-form' lay-filter=\"solution_input\"> \n" +
        "      <textarea placeholder=\"请输入内容\" class=\"layui-textarea\" name=\"solution\"></textarea>\n" +
        "</form>"

    function update_problem_status(msg_id, engineer) {
        layui.use('layer', function () {
            layer.open({
                type: 1,
                title: "填写你的解决方案",
                scrollbar: false,
                content: form_solution,
                btn: ['本部门内解决', '非本部门内解决'],
                btn1: function () {
                    f(0)
                },
                btn2: function () {
                    f(1)
                    return false
                },
                // btn3: function () {
                //     f(1, 0)
                //     console.log("btn3")
                // },
                area: ['42%', '35%']

            });

            function f(index) {
                layui.use('form', function () {
                    const form = layui.form;
                    let data = form.val('solution_input');
                    if (data['solution'] !== "") {
                        data['engineer'] = engineer
                        data['hq'] = msg_id
                        data['type'] = pageOptions.type
                        data['status'] = 1
                        if (index === 0) {
                            data['processorDepartment'] = 0;
                        } else {
                            data['processorDepartment'] = 1;
                        }
                        let number = ajax_update_status(data);
                        console.log(number)
                        parent.layer.closeAll()
                        layer.msg('已经解决啦');
                        document.getElementById(msg_id).innerHTML = ''
                    } else {
                        layer.msg('你还没有输入解决方案哦');
                    }
                })
            }

            // layui.use('form', function () {
            //     const form = layui.form;
            //     //表单取值
            //     layui.$('#mineSolution').on('click', function () {
            //         console.log("mineSolution")
            //
            //         let data = form.val('solution_input');
            //         // if (data['solution'] !== "") {
            //         //     data['engineer'] = engineer
            //         //     data['hq'] = msg_id
            //         //     data['type'] = pageOptions.type
            //         //     data['status'] = pageOptions.status
            //         //     ajax_update_status(data)
            //         //     parent.layer.closeAll()
            //         //     layer.msg('已经解决啦');
            //         //     document.getElementById(msg_id).innerHTML = ''
            //         //     //关闭悬浮框
            //         // } else {
            //         //     layer.msg('你还没有输入解决方案哦');
            //         // }
            //     });
            //     layui.$('#otherSolution').on('click', function () {
            //         console.log("other")
            //         // let data = form.val('solution_input');
            //         // if (data['solution'] !== "") {
            //         //     data['engineer'] = engineer
            //         //     data['hq'] = msg_id
            //         //     data['type'] = pageOptions.type
            //         //     data['status'] = pageOptions.status
            //         //     ajax_update_status(data)
            //         //     parent.layer.closeAll()
            //         //     layer.msg('已经解决啦');
            //         //     document.getElementById(msg_id).innerHTML = ''
            //         //     //关闭悬浮框
            //         // } else {
            //         //     layer.msg('你还没有输入解决方案哦');
            //         // }
            //     });
            //
            // });
        })
    }

    //ajax请求修改问题状态
    function ajax_update_status(options) {
        let return_data = 0
        $.ajax({
            url: "/update_msg_status"
            , data: {
                data: JSON.stringify(options)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                // console.log(data)
                return_data = data
            }
        })
        return return_data
    }

    function update_message_status(msg_id, engineer) {
        let data = {}
        data['engineer'] = engineer
        data['hq'] = msg_id
        data['type'] = pageOptions.type
        data['status'] = pageOptions.status
        ajax_update_status(data)
        layer.msg('已经修改成功');
        document.getElementById(msg_id).innerHTML = ''
    }

    function compare(property) {
        return function (obj1, obj2) {
            const value1 = obj1[property];
            const value2 = obj2[property];
            return value1 - value2;     // 升序
        }
    }

    function ask_all_group_message(data) {
        $.ajax({
            url: "/all_group_message"
            , data: {
                data: JSON.stringify(data)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                data.sort(compare("time"))
                add_group_info(data)
                // console.log(data)
            }
        })
    }

    function selMsgByGroup(id, cp_name, count_msg) {
        pageOptions.hq = count_msg
        pageOptions.cp_id = id
        pageOptions.cp_name = cp_name
        document.getElementById('thGroupName').innerText = cp_name
        // console.log(JSON.stringify(pageOptions))
        $.ajax({
            url: "/msg_byGroupId"
            , data: {
                data: JSON.stringify(pageOptions)
            }
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function (data) {
                add_msg_list(data)
            }
        })
    }

    //向问题列表添加具体问题
    function add_msg_list(data) {
        let temp_message_list
        let messageList = document.getElementById("message_list")
        messageList.innerHTML = ''
        for (let i = 0; i < data.length; i++) {
            temp_message_list = div_message_list.replace("text", data[i]['text'])
            temp_message_list = temp_message_list.replace("群名", data[i]['cpName'])
            temp_message_list = temp_message_list.replace("engineer", data[i]['engineer'])
            temp_message_list = temp_message_list.replace("time", data[i]['admin'])
            temp_message_list = temp_message_list.replace("hq_id", data[i]['hq'])
            if (data[i]['status'] === 0) {
                //按钮
                let temp_button_update_msg_status = button_update_msg_status.replace("msg_id", data[i]['hq'])
                let temp_button_add_msg_status = button_update_msg_status.replace("msg_id", data[i]['hq'])
                temp_button_add_msg_status = temp_button_add_msg_status.replace("engineer", data[i]['engineer'])
                temp_button_add_msg_status = temp_button_add_msg_status.replace("trOnClick", 'update_message_status')
                temp_button_update_msg_status = temp_button_update_msg_status.replace("engineer", data[i]['engineer'])
                // temp_button_update_msg_status = temp_button_update_msg_status.replace("engineer", data[i])
                // pageOptions.engineer_id=data[i]['engineer']
                if (data[i]['type'] === 'message') {
                    temp_button_update_msg_status = temp_button_update_msg_status.replace("update_message_status", 'update_message_status')
                } else {
                    temp_button_update_msg_status = temp_button_update_msg_status.replace("update_message_status", 'update_problem_status')
                    temp_button_add_msg_status = temp_button_add_msg_status.replace("update_message_status", 'add_msg_status')
                    temp_button_add_msg_status = temp_button_add_msg_status.replace("关闭", '编辑')
                    temp_button_update_msg_status += temp_button_add_msg_status
                }
                temp_message_list = temp_message_list.replace("button", temp_button_update_msg_status)
                // temp_message_list = temp_message_list.replace("button", button_update_msg_status.replace("engineer", data[i]['engineer']))
            } else if (data[i]['status'] === 1) {
                if (data[i]['type'] === 'message') {
                    temp_message_list = temp_message_list.replace("button", "<br>【" + data[i]['processor'] + "】")
                } else {
                    //解决人
                    temp_message_list = temp_message_list.replace("button", data[i]['solution'] + "<br>【" + data[i]['processor'] + "】")
                }
            }
            messageList.innerHTML += temp_message_list
        }
    }

    function add_group_info(data) {
        let div_group_msg_temp;
        group_list.innerHTML = ""
        for (let i = 0; i < data.length; i++) {
            div_group_msg_temp = div_group_msg.replace("cp_name", data[i]["cpName"] + "【" + data[i]["hq"] + "】")
            div_group_msg_temp = div_group_msg_temp.replace("群名", data[i]["cpName"])
            div_group_msg_temp = div_group_msg_temp.replace("cp_id", data[i]["cpId"])
            // div_group_msg_temp = div_group_msg_temp.replace("数量", "数量" + data[i]["hq"])
            div_group_msg_temp = div_group_msg_temp.replace("待处理数量", data[i]["hq"])
            group_list.innerHTML = group_list.innerHTML + div_group_msg_temp
        }
    }


    document.getElementById('problemOn').click()
    // console.log(problemOn)
    ask_all_group_message(pageOptions)
    ask_all_message(pageOptions)
    ask_allNeedAddProblemStatus_engineer()
    ask_over_time_data()
    dataChange('now')
</script>
</body>
</html>
